package com.qili.controller;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.entity.CurrentUser;
import com.qili.entity.exam.*;
import com.qili.entity.exam.dto.ExExamDTO;
import com.qili.entity.exam.dto.ExQuestionDTO;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.exception.MyException;
import com.qili.mapper.exam.ExExamMapper;
import com.qili.mapper.exam.ExQuestionMapper;
import com.qili.mapper.exam.ExStuExamCopyMapper;
import com.qili.mapper.exam.ExStuExamDetailMapper;
import com.qili.service.exam.*;
import com.qili.service.supervisor.SupervisorFileService;
import com.qili.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhangxiaopeng
 * @date 2021-08-24
 * @description综合服务 客户端
 */
@Controller
@RequestMapping("/exam/client")
public class ExamController {

    @Autowired
    ExExamService exExamService;
    @Autowired
    ExExamMapper exExamMapper;
    @Autowired
    UploadUtil uploadUtil;
    @Autowired
    SupervisorFileService supervisorFileService;
    @Autowired
    ExExamPaperService exExamPaperService;
    @Autowired
    ExPaperQuestionService exPaperQuestionService;
    @Autowired
    ExQuestionMapper exQuestionMapper;
    @Autowired
    ExQuAnswerService exQuAnswerService;
    @Autowired
    ExStuExamService exStuExamService;
    @Autowired
    ExStuExamDetailMapper exStuExamDetailMapper;
    @Autowired
    ExStuExamCopyMapper exStuExamCopyMapper;

    /**
    * @Description:点击考试查看是否已考试
    * @param ese
    * @Date:17:11 2021-08-27
    */
    @GetMapping("/selectDetail")
    @ResponseBody
    public JsonUtil selectDetail(ExStuExamCopy ese) throws ParseException {
        JsonUtil json=new JsonUtil();
        ExExam exam=exExamMapper.selectByPrimaryKey(ese.getExamId());
        //判断是否在考试时间段内
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start =  df.parse(exam.getStartTime());
        Date end =  df.parse(exam.getEndTime());
        Date data=DateUtil.getCurrentDateTime();
        int i=DateUtil.comparetodate(data,start);
        int j=DateUtil.comparetodate(data,end);
        if(i==-1||j==1){
            json.setFlag(false);
            json.setMsg("不在考试时间内!");
            return json;
        }
        //判断是正式考试还是练习  001正式考试  002测试考试
        if("001".equals(exam.getType())){
            //判断是否已经考过
            ese.setUserId(CommonUtil.getUserId());
            ExStuExamCopy stdList=exStuExamCopyMapper.selectOne(ese);
            if(stdList!=null&&StringUtil.isNotBlank(stdList.getState())&&"002".equals(stdList.getState())){
                json.setFlag(false);
                json.setMsg("你已完成该考试,请不要重复参加考试!");
            }else{
                json.setFlag(true);
            }
        }else{
            json.setFlag(true);
        }
        return json;
    }

    /**
    * @Description:温馨提示
    * @param model
    * @Date:16:06 2021-08-24
    */
    @GetMapping("/prompt")
    public String prompt(Model model,ExExamDTO dto){
        List<ExExamDTO> ksList = exExamMapper.selectExamList(dto);
        if(ksList!=null&&ksList.size()>0) {
            model.addAttribute("ks",ksList.get(0));
        }
        return "/examination/prompt";
    }

    /**
    * @Description:考试、试题查询
    * @param model
    * @param dto
    * @Date:10:48 2021-08-25
    */
    @GetMapping("/testContentDoExam")
    public String updateTestContent(Model model,ExExamDTO dto){
        //考试数据
        ExExamDTO ks = exExamMapper.selectInExam(dto);
        model.addAttribute("ks",ks);
        //根据考试id查询对应的试卷
        ExExamPaper expaper=new ExExamPaper();
        expaper.setExamId(ks.getExamId());
        List<ExExamPaper> examPaper=exExamPaperService.select(expaper);
        //获取当前登录人
        CurrentUser user = CommonUtil.getUser();
        model.addAttribute("userName",user.getRealName());
        //从试卷中随机获取一条数据用作考试
        try{
                Example example=new Example(ExStuExamCopy.class);
                Example.Criteria criterias = example.createCriteria();
                criterias.andEqualTo("examId",dto.getExamId());
                criterias.andEqualTo("userId",user.getId());
                criterias.andNotEqualTo("state","000");
                example.setOrderByClause("create_date desc");
                List<ExStuExamCopy> exstucopyList=exStuExamCopyMapper.selectByExample(example);
                //没有值走新增  有值是没有交卷点了保存这次接着考
                if(exstucopyList!=null&&exstucopyList.size()>0&&"001".equals(exstucopyList.get(0).getState())){
                    //剩余考试时长
                    model.addAttribute("time",exstucopyList.get(0).getAnswerTime());
                    //查出对应的考生明细数据 只查有答案的
                    Map map=new HashMap();
                    map.put("exStuExamId",exstucopyList.get(0).getStuExamId());
//                    map.put("answer","answer");
                    List<ExStuExamDetail> exstuList=exStuExamDetailMapper.selectExamList(map);
                    //查询出每道试题类型
                    if(exstuList!=null&&exstuList.size()>0){
                        for(int i=0;i<exstuList.size();i++){
                            ExQuestion exQuestion=exQuestionMapper.selectByPrimaryKey(exstuList.get(i).getQuId());
                            exstuList.get(i).setQuType(exQuestion.getQuType());
                        }
                        //查询对应的试题和答案
                        selectExQuAnswer(exstuList.get(0).getPaperId(), model);
                        model.addAttribute("exstuList",exstuList);
                        model.addAttribute("paperId",exstuList.get(0).getPaperId());
                    }
                }else {
                    if (examPaper != null && examPaper.size() > 0) {
                        Random random = new Random();
                        int n = random.nextInt(examPaper.size());
                        //试卷id
                        String paperId=examPaper.get(n).getPaperId();
                        model.addAttribute("paperId",paperId);
                        //查询对应的试题和答案
                        selectExQuAnswer(paperId, model);
                        //开始考试时间
                        model.addAttribute("startTime",DateUtil.getCurrentDateString());
                    }
                }

        }catch (Exception e) {
            e.printStackTrace();
        }

        return "/examination/test_content";
    }

    /**
     * @Description:考试详情
     * @param model
     * @param copy
     * @Date:10:48 2021-08-30
     */
    @GetMapping("/ExamDetails")
    public String ExamDetails(Model model,ExStuExamCopy copy){
        try{
            //查询对应考生考试
            ExStuExamCopy exstucopy=exStuExamCopyMapper.selectOne(copy);
            //考试数据
            ExExamDTO dto=new ExExamDTO();
            dto.setExamId(exstucopy.getExamId());
            ExExamDTO ks = exExamMapper.selectInExam(dto);
            model.addAttribute("ks",ks);
            //分数
            model.addAttribute("score",exstucopy.getScore());
            //根据考试id查询对应的试卷
            ExExamPaper expaper=new ExExamPaper();
            expaper.setExamId(ks.getExamId());
            List<ExExamPaper> examPaper=exExamPaperService.select(expaper);
            //获取当前登录人
            CurrentUser user = CommonUtil.getUser();
            model.addAttribute("userName",user.getRealName());

            //查出对应的考生明细数据 只查有答案的
            Map map=new HashMap();
            map.put("exStuExamId",exstucopy.getStuExamId());
            map.put("answer","answer");
            List<ExStuExamDetail> exstuList=exStuExamDetailMapper.selectExamList(map);
            //查询出每道试题类型
            for(int i=0;i<exstuList.size();i++){
                ExQuestion exQuestion=exQuestionMapper.selectByPrimaryKey(exstuList.get(i).getQuId());
                exstuList.get(i).setQuType(exQuestion.getQuType());
            }
            model.addAttribute("exstuList",exstuList);
            //查询对应的试题和答案
            selectExQuAnswer(exstuList.get(0).getPaperId(), model);
            model.addAttribute("paperId",exstuList.get(0).getPaperId());
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "/examination/result";
    }

    //查询随机获取的试卷的试题
    public void selectExQuAnswer(String paperId,Model model){
        //查询试卷和试题的关联表
        Map map=new HashMap<>();
        map.put("paperId",paperId);
        List<ExQuestionDTO> question=exQuestionMapper.selectQuestion(map);
        //查询问题下的答案
        for(int i=0;i<question.size();i++){
            Example example=new Example(ExQuAnswer.class);
            Example.Criteria criterias = example.createCriteria();
            criterias.andEqualTo("quId",question.get(i).getQuId());
            example.setOrderByClause("serial");
            List<ExQuAnswer> exQuAnswer=exQuAnswerService.selectByExample(example);
            StringJoiner join=new StringJoiner(",");
            for(int j=0;j<exQuAnswer.size();j++){
                if("1".equals(exQuAnswer.get(j).getIsRight())){
                    join.add(exQuAnswer.get(j).getAnswerContent());
                }
            }
            question.get(i).setAnswer(join.toString());
            //试题类型 001 单选  002 多选 003 判断  004 填空  005 问答
            if("001".equals(question.get(i).getQuType())){
                question.get(i).setExDxList(exQuAnswer);
            }else if("002".equals(question.get(i).getQuType())){
                question.get(i).setExDuoxList(exQuAnswer);
            }else if("003".equals(question.get(i).getQuType())){
                question.get(i).setExPdList(exQuAnswer);
            }else if("004".equals(question.get(i).getQuType())){
                question.get(i).setExTkList(exQuAnswer);
            }else if("005".equals(question.get(i).getQuType())){
                question.get(i).setExWdList(exQuAnswer);
            }
        }
        model.addAttribute("st",question);
    }

    /**
    * @Description:提交试卷
    * @param exDto
    * @Date:11:52 2021-08-27
    */
    @PostMapping("/insertExam")
    @ResponseBody
    public JsonUtil insertExam(ExQuestionDTO exDto){
        JsonUtil json=new JsonUtil();
        try {
            //考试数据
            ExExamDTO dto=new ExExamDTO();
            dto.setExamId(exDto.getExamId());
            ExExamDTO ks = exExamMapper.selectInExam(dto);
            //判断是否全部是单选、多选、判断 如果是算出分数
            Boolean bool=false;
            if(StringUtils.isNotBlank(exDto.getPaperId())) {
                bool=bool(exDto.getPaperId());
            }
            //维护考生考试表
            ExStuExam stuExam=new ExStuExam();
            stuExam.setExamId(exDto.getExamId());
            stuExam.setUserId(CommonUtil.getUserId());
//            stuExam=exStuExamService.selectOne(stuExam);
            // 不使用  selectOne 若有误操作查询多条 报错
            stuExam=exStuExamService.select(stuExam).get(0);
            //答题次数
            if(stuExam.getNum()!=null&&stuExam.getNum()>0) {
                stuExam.setNum(stuExam.getNum() + 1);
            }else{
                stuExam.setNum(1);
            }
//            //状态改为提交
//            stuExam.setState("002");
            exStuExamService.updateByPrimaryKeySelective(stuExam);
            //答题时长
            Integer time=Integer.parseInt(ks.getTotalTime())-Integer.parseInt(exDto.getAnswerTime());
            //维护考生考生副表
            Integer score=0;
            ExStuExamCopy examCopy=new ExStuExamCopy();
            examCopy.setState("002");//状态
            examCopy.setSubmitTime(DateUtil.getCurrentDateString());//答题交卷时间
            examCopy.setAnswerTime(time.toString());
            updateStuCopy(exDto,stuExam,examCopy,score,bool);

            if(bool){
                json.setData(score);
            }
            json.setFlag(true);
        }catch (Exception e){
          e.printStackTrace();
          json.setFlag(false);
        }
        return json;
    }
    //判断是否全部是单选、多选、判断
    private Boolean bool(String paperId){
        //根据试卷id查询对应的试题
        ExPaperQuestion epq=new ExPaperQuestion();
        epq.setPaperId(paperId);
        List<ExPaperQuestion> epqList =exPaperQuestionService.select(epq);
        int num = 0;
        for (int i = 0; i < epqList.size(); i++) {
            ExQuestion exQuestion=exQuestionMapper.selectByPrimaryKey(epqList.get(i).getQuId());
            if("001".equals(exQuestion.getQuType())||"002".equals(exQuestion.getQuType())||"003".equals(exQuestion.getQuType())){
                num++;
            }
        }
        if(num==epqList.size()){
            return true;
        }else{
            return false;
        }
    }

    /**
     * @Description:保存试卷
     * @param exDto
     * @Date:11:52 2021-08-27
     */
    @GetMapping("/insertSaveExam")
    @ResponseBody
    public JsonUtil insertSaveExam(ExQuestionDTO exDto){
        JsonUtil json=new JsonUtil();
        try {
            //考试数据
            ExExamDTO dto=new ExExamDTO();
            dto.setExamId(exDto.getExamId());
            ExExamDTO ks = exExamMapper.selectInExam(dto);
            //维护考生考试表
            ExStuExam stuExam=new ExStuExam();
            stuExam.setExamId(exDto.getExamId());
            stuExam.setUserId(CommonUtil.getUserId());
            stuExam=exStuExamService.selectOne(stuExam);
//            exStuExamService.updateByPrimaryKeySelective(stuExam);
            Boolean bool=false;
            //维护考生考试副表
            ExStuExamCopy examCopy=new ExStuExamCopy();
            examCopy.setState("001");//状态
            //答题时长  保存试卷时存放剩余答题时长
            examCopy.setAnswerTime(exDto.getAnswerTime());
            updateStuCopy(exDto,stuExam,examCopy,0,bool);
            json.setFlag(true);
        }catch (Exception e){
            e.printStackTrace();
            json.setFlag(false);
        }
        return json;
    }

    //考试生考试副表
    private void updateStuCopy(ExQuestionDTO exDto,ExStuExam stuExam,ExStuExamCopy examCopy,Integer score,Boolean bool){
        try{
            //查询考试生考试表
            Example example=new Example(ExStuExamCopy.class);
            Example.Criteria criterias = example.createCriteria();
            criterias.andEqualTo("examId",exDto.getExamId());
            criterias.andEqualTo("userId",CommonUtil.getUserId());
            criterias.andIsNull("submitTime");//交卷时间
            example.setOrderByClause("create_date desc");
            List<ExStuExamCopy> ecopy=exStuExamCopyMapper.selectByExample(example);
            examCopy.setNum(stuExam.getNum());
            examCopy.setPaperId(exDto.getPaperId());
            examCopy.setExamId(exDto.getExamId());
            examCopy.setUserId(CommonUtil.getUserId());
            if(StringUtil.isNotBlank(exDto.getStartTime())){
                examCopy.setStartTime(exDto.getStartTime());
            }
            int i=0;
            if(ecopy!=null&&ecopy.size()>0){
                examCopy.setStuExamId(ecopy.get(0).getStuExamId());
                i=exStuExamCopyMapper.updateByPrimaryKeySelective(examCopy);
            }else {
                examCopy.setStuExamId(IdUtil.simpleUUID());
                examCopy.setIsMark("0");
                examCopy.setCreateBy(CommonUtil.getUserId());
                examCopy.setCreateDate(DateUtil.getCurrentDateString());
                i=exStuExamCopyMapper.insert(examCopy);
            }
            if(i>0){
                //维护考生考试明细表
                if(exDto.getExQuList()!=null&&exDto.getExQuList().size()>0){
                    updateStuDetail(bool,exDto,score,examCopy.getStuExamId());
                }
            };
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //维护考生考试明细表
    public void updateStuDetail(Boolean bool,ExQuestionDTO exDto,Integer score,String stuCopId){
        List<ExQuAnswer> exQuList=exDto.getExQuList();
        //查询是否是第一次保存或提交
        ExStuExamDetail ese=new ExStuExamDetail();
        ese.setExStuExamId(stuCopId);
        List<ExStuExamDetail> eseList=exStuExamDetailMapper.select(ese);
        //考生明细表是否有数据有数据是之前保存进行维护的没数据新增
        if(eseList!=null&&eseList.size()>0){
            //前台传过来的下标从1开始
            for(int i=1;i<exQuList.size();i++){
                //查询对应考生考试明细表  添加考生答案
                ExStuExamDetail exStuExamDetail=new ExStuExamDetail();
                if(bool) {
                    //查出每题的分值
                    ExPaperQuestion exPaperQuestion = new ExPaperQuestion();
                    exPaperQuestion.setQuId(exQuList.get(i).getQuId());
                    exPaperQuestion.setPaperId(exDto.getPaperId());
                    exPaperQuestion = exPaperQuestionService.selectOne(exPaperQuestion);
                    //查出每题的正确答案
                    Example example=new Example(ExQuAnswer.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("quId",exQuList.get(i).getQuId());
                    criteria.andEqualTo("isRight","1");
                    example.setOrderByClause("serial");
                    List<ExQuAnswer> exQuAnswer = exQuAnswerService.selectByExample(example);
                    //将正确答案拼接
                    StringJoiner joiner=new StringJoiner(",");
                    if(exQuAnswer!=null && exQuAnswer.size() > 0){
                        for(ExQuAnswer eqa:exQuAnswer){
                            joiner.add(eqa.getAnswerContent());
                        }
                    }
                    //判断填写的答案是否正确 评出分值
                    if (StringUtil.isNotBlank(exQuList.get(i).getAnswerContent()) && StringUtil.isNotBlank(joiner.toString())) {
                        if ((exQuList.get(i).getAnswerContent()).equals(joiner.toString())) {
                            exStuExamDetail.setScore(exPaperQuestion.getScore());
                        } else {
                            exStuExamDetail.setScore("0");
                        }
                    } else {
                        exStuExamDetail.setScore("0");
                    }
                    score += Integer.parseInt(exStuExamDetail.getScore());
                }
                exStuExamDetail.setExStuExamId(stuCopId);
                exStuExamDetail.setQuId(exQuList.get(i).getQuId());
                exStuExamDetail=exStuExamDetailMapper.selectOne(exStuExamDetail);
                if(StringUtil.isNotBlank(exQuList.get(i).getAnswerContent())) {
                    exStuExamDetail.setAnswer(exQuList.get(i).getAnswerContent());
                }
                exStuExamDetailMapper.updateByPrimaryKeySelective(exStuExamDetail);
            }
            //全是单选、多选、判断算出分值
            if(bool){
                ExStuExamDetail exStuExamDetail=new ExStuExamDetail();
                giveAMark(exDto,score,stuCopId,exStuExamDetail,exQuList);
            }
        }else {
            //全是单选、多选、判断算出分值
            for(int i=1;i<exQuList.size();i++){
                //查询对应考生考试明细表  添加考生答案
                ExStuExamDetail exStuExamDetail=new ExStuExamDetail();
                if(bool) {
                    //查出每题的分值
                    ExPaperQuestion exPaperQuestion = new ExPaperQuestion();
                    exPaperQuestion.setQuId(exQuList.get(i).getQuId());
                    exPaperQuestion.setPaperId(exDto.getPaperId());
                    exPaperQuestion = exPaperQuestionService.selectOne(exPaperQuestion);
                    //查出每题的正确答案
                    Example example=new Example(ExQuAnswer.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("quId",exQuList.get(i).getQuId());
                    criteria.andEqualTo("isRight","1");
                    example.setOrderByClause("serial");
                    List<ExQuAnswer> exQuAnswer = exQuAnswerService.selectByExample(example);
                    //将正确答案拼接
                    StringJoiner joiner=new StringJoiner(",");
                    if(exQuAnswer!=null && exQuAnswer.size() > 0){
                        for(ExQuAnswer eqa:exQuAnswer){
                            joiner.add(eqa.getAnswerContent());
                        }
                    }
                    //判断填写的答案是否正确 评出分值
                    if (StringUtil.isNotBlank(exQuList.get(i).getAnswerContent()) && StringUtil.isNotBlank(joiner.toString())) {
                        if ((exQuList.get(i).getAnswerContent()).equals(joiner.toString())) {
                            exStuExamDetail.setScore(exPaperQuestion.getScore());
                        } else {
                            exStuExamDetail.setScore("0");
                        }
                    } else {
                        exStuExamDetail.setScore("0");
                    }
                    score += Integer.parseInt(exStuExamDetail.getScore());
                }
                exStuExamDetail.setExamId(exDto.getExamId());
                exStuExamDetail.setPaperId(exDto.getPaperId());
                exStuExamDetail.setQuId(exQuList.get(i).getQuId());
                exStuExamDetail.setUserId(CommonUtil.getUserId());
                if(StringUtil.isNotBlank(exQuList.get(i).getAnswerContent())) {
                    exStuExamDetail.setAnswer(exQuList.get(i).getAnswerContent());
                }
                exStuExamDetail.setStuExamDetailId(IdUtil.simpleUUID());
                exStuExamDetail.setSerial(i);
                exStuExamDetail.setCreateBy(CommonUtil.getUserId());
                exStuExamDetail.setCreateDate(DateUtil.getCurrentDateString());
                exStuExamDetail.setExStuExamId(stuCopId);
                exStuExamDetailMapper.insert(exStuExamDetail);
            }
            if(bool){
                ExStuExamDetail exStuExamDetail=new ExStuExamDetail();
                giveAMark(exDto,score,stuCopId,exStuExamDetail,exQuList);
            }
        }
    }

    //全是单选算出分值
    public void giveAMark(ExQuestionDTO exDto,Integer score,String stuCopId, ExStuExamDetail exStuExamDetail,List<ExQuAnswer> exQuList){
        ExExam exam=exExamService.selectByPrimaryKey(exDto.getExamId());
        Integer passScore=Integer.parseInt(exam.getPassScore());
        ExStuExamCopy examCopy=new ExStuExamCopy();
        examCopy.setStuExamId(stuCopId);
        //判断是否及格
        if(score>=passScore){
            examCopy.setIsJg("1");
        }else{
            examCopy.setIsJg("0");
        }
        examCopy.setIsMark("1");
        examCopy.setScore(score.toString());
        exStuExamCopyMapper.updateByPrimaryKeySelective(examCopy);
    }

}
